#include <Misc.au3>
#include <ScreenCapture.au3>

;-------- Status Logging (CSV) items
$statusNeedRepair=0
$statusRepaired=0
$statusShrine=0
$statusEnteredManor=0
$statusRessurectOnManorEntrance=0
$statusLegendaryDrop=0
$statusLegendaryFailure=0
$statusDisconnectRecovery=0
$statusDied=0
$statusRessurectFired=0
$statusShrineType=0

$statustotalNeedRepair=0
$statustotalRepaired=0
$statustotalShrine=0
$statustotalEnteredManor=0
$statustotalRessurectOnManorEntrance=0
$statustotalLegendaryDrop=0
$statustotalLegendaryFailure=0
$statustotalDisconnectRecovery=0
$statustotalDied=0
$statustotalRessurectFired=0
writeheader()
;--------

$manualpickup = 0 ; Set this to 0 if you just want to exit if you're dead and a legendary drops. Setting it to 1 means you will manually pick it up. Only really useful if you are running EmailMonster for email notifications.

$get63s = IniRead("settings.ini", "loot", "get63weapons", 1)
$getall63s = IniRead("settings.ini", "loot", "getall63s", 0)
$allYellow = IniRead("settings.ini", "loot", "getallyellows", 0)
$demonicessence = IniRead("settings.ini", "loot", "getdemonicessences", 0)
$getgold = IniRead("settings.ini", "loot", "getgold", 1)
$skiprares = IniRead("settings.ini", "loot", "skiprares", 0)

$disconnects = 0
$deaths = 1
$runs = 1

$debug = IniRead("settings.ini", "system", "debug", 0)

$iniminruns = IniRead("settings.ini", "run", "minruns", 380)
$inimaxruns = IniRead("settings.ini", "run", "maxruns", 420)
$infinitemode = IniRead("settings.ini", "run", "infinitemode", 0)

$potionbutton = IniRead("settings.ini", "other", "potionbutton", "Q")

$maxruns = Random($iniminruns,$inimaxruns,1) ;Maximum number of runs that the bot should do
$inilagfactor = IniRead("settings.ini", "system", "lagfactor", 0)
$lagfactor = $inilagfactor * 1000 ;Lag factor, pauses for slow machines
$inirunspeed = IniRead("settings.ini", "run", "runspeed", 0)
$runspeed = 1+((24 - $inirunspeed)/100) ;Run speed. Bot is programmed to expect 24% move speed. 24 - provided value = % longer we have to wait to move to a location

$lootoptions = "Only Legendaries and Jewelry"
If $allYellow = 1 Then
	$lootoptions = "All Yellows, Legendaries and Jewelry "
ElseIf $getall63s = 1 Then
	$lootoptions = "All ilvl 63 Yellows, Legendaries, and Jewelry "
ElseIf $get63s = 1 Then
	$lootoptions = "All ilvl 63 1-Hander Yellows, Legendaries, and Jewelry "
EndIf

logmessage("Running " & $maxruns & " runs with a " & $inilagfactor & " second delay at " & $inirunspeed & "% run speed. " & $lootoptions & "will be picked up.")
;MsgBox(0, "Settings", "Running " & $maxruns & " runs with a " & $inilagfactor & " second delay at " & $inirunspeed & "% run speed. " & $lootoptions & "will be picked up.")

$previousExpBubble = 0
; Determines what % into current level the player is
Func checkExperienceLevel()
	; 625, 986  x 66,7
	; 69 to next
	; 0x303C3A
	$x = 625 + ($previousExpBubble * 69)

	Local $coord = PixelSearch($x, 986, $x+66, 986+7, 0x303C3A, 12)
	If @error Then
		MsgBox(0, "Nope", @error)
		return
	Endif
	MsgBox(0, $coord[0], $coord[1])
EndFunc

; Assumes craft window is open and
; desired recipe is selected
; - will keep clicking [craft] 'til can't no mo'
Func craftTilDone($maxCrafts = 100)
	$tries = 0
	While $maxCrafts > 0
		$color = PixelGetColor(155, 765)
		if($color <> 0x664542) Then
			if $tries = 1 Then
				Return
			EndIf

			fuzzysleep(100)
			$tries = 1
		Else
			$tries = 0
			fuzzyclick("left", 263, 780)
			fuzzysleep(3300)
			$maxCrafts = $maxCrafts - 1
		EndIf
	WEnd
EndFunc

;1-4 are skills
;5 is left button skill
;6 is right button skill
Func spellReady($slot)
	; 66px between
	$x = 592 + ($slot*66)
	$y = 1000

	; Two mouse slots are 2 pixels shifted down
	If($slot>=5) Then
		$y += 2
	EndIf

	$color = PixelGetColor($x,$y)
	If($color = 0x191C18 OR $color = 0x191D18 OR $color = 0x1C1F1A OR $color =  0x1B1F1A) Then
		Return 1
	EndIf

	Return 0
EndFunc

;Casts specified spell *If it is available*
;1-4 skill #.  Not currently functional for button skills
Func castSpell($slot)
	If(spellReady($slot) = 0) Then
		;call("logmessage", "Tried to cast "&$slot&" but it wasn't ready.")
		Return 0
	EndIf

	;call("logmessage", "Casted " & $slot & ".")
	Send($slot)
EndFunc

;if specified key is pressed, execute function
; Example to handle F1
;     processkey('70', "methodname")
 Func processkey($key, $function)
	If _IsPressed($key) Then
		While _IsPressed($key)
			Sleep(100)
		WEnd
		call($function)
	EndIf
 EndFunc

Func logmessage($text)
	Local $time = @hour & ":" & @MIN & ":" & @SEC
	Local $file = FileOpen("log.txt", 1)

	; Check if file opened for writing OK
	If $file = -1 Then
		Return
	EndIf

	FileWrite($file, $time)
	FileWrite($file, " " & $text & @CRLF)

	FileClose($file)
EndFunc

Func checkdead($log = 1)
	If checkdead2($log,0x3F3F3F) = 1 OR checkdead2($log,0xFFFFFF) Then
		Return 1
	EndIf
	Return 0
EndFunc

Func checkdead2($log,$color)
	;Check dead
	Local $coord = PixelSearch(500, 200, 550, 250, $color)
	If Not @error Then
		Local $coord2 = PixelSearch(1300, 200, 1350, 250, $color)
		If Not @error Then
			If $log = 1 Then
				logmessage("Death #" & $deaths)
				screenshot("death")
				$deaths = $deaths + 1
				$statusDied=1
			EndIf
			Return 1
		EndIf
	EndIf
EndFunc

Func screenshot($text)
	;$sFileName = "C:\Users\Quinn\Desktop\D3\Screenshots\" & $text & @MON & "_" & @MDAY & "_" & @YEAR & "_" & @hour & "_" & @MIN & "_" & @SEC & ".jpg"
	$sFileName = @ScriptDir & "\Screenshots\" & $text & @MON & "_" & @MDAY & "_" & @YEAR & "_" & @hour & "_" & @MIN & "_" & @SEC & ".jpg"
	logmessage("Screenshotting " & $sFileName)
	_ScreenCapture_Capture($sFileName)
EndFunc

Func fuzzyclick($button, $xcoord, $ycoord, $fudge = 10)
	Local $newxcoord = Random($xcoord - $fudge, $xcoord + $fudge, 1)
	Local $newycoord = Random($ycoord - $fudge, $ycoord + $fudge, 1)

	If $newxcoord < 0 Then
		$newxcoord = 0
	EndIf
	If $newxcoord > 1920 Then
		$newxcoord = 1920
	EndIf
	If $newycoord < 0 Then
		$newycoord = 0
	EndIf
	If $newycoord > 1080 Then
		$newycoord = 1080
	EndIf

	MouseClick($button, $newxcoord, $newycoord)
EndFunc

Func fuzzymove($xcoord, $ycoord, $fudge = 10)
	Local $newxcoord = Random($xcoord - $fudge, $xcoord + $fudge, 1)
	Local $newycoord = Random($ycoord - $fudge, $ycoord + $fudge, 1)

	If $newxcoord < 0 Then
		$newxcoord = 0
	EndIf
	If $newxcoord > 1920 Then
		$newxcoord = 1920
	EndIf
	If $newycoord < 0 Then
		$newycoord = 0
	EndIf
	If $newycoord > 1080 Then
		$newycoord = 1080
	EndIf

	MouseMove($newxcoord, $newycoord)
EndFunc

Func findcolor()
	Local $color = 0x767676
	Local $arr = PixelSearch(0,0,1920,1080,$color)
	If IsArray($arr) Then
		;MouseMove($arr[0],$arr[1])
		MsgBox(0,"Checksum",PixelChecksum($arr[0],$arr[1], $arr[0]+27, $arr[1]+10))
	EndIf

	;amulet color: 0x767676
	;amulet checksum: 1085905009
EndFunc

Func findring()
	Local $color = 0xFFFF00

	Send("{ALT}")
	fuzzysleep(200)

	;Find Top Rare
	Local $ringloc1 = PixelSearch(0,0,1920,1080,$color)
	If IsArray($ringloc1) Then
		MouseMove($ringloc1[0], $ringloc1[1])
		;-100,-400
		If $allYellow = 1 Or call("getsum") = 1 Then
			MouseClick("left", $ringloc1[0], $ringloc1[1])
			Sleep(1000)
			Return 1
		EndIf
	Else
		Return 0; Found nothing, exit early
	EndIf

	;Find Bot Rare
	Local $ringloc2 = PixelSearch(1920,1080,0,0,$color)
	If IsArray($ringloc2) Then
		MouseMove($ringloc2[0], $ringloc2[1])
		If $allYellow = 1 Or call("getsum") = 1 Then
			MouseClick("left", $ringloc2[0], $ringloc2[1])
			Sleep(1000)
			Return 1
		EndIf
	Else
		Return 0
	EndIf

	Send("{ALT}")
	fuzzysleep(200)

	;Find Left Rare
	Local $ringloc3 = PixelSearch(0,0, $ringloc1[0]-100,1080,$color)
	If IsArray($ringloc3) Then
		MouseMove($ringloc3[0], $ringloc3[1])
		if $allYellow = 1 Or call("getsum") = 1 Then
			MouseClick("left", $ringloc3[0], $ringloc3[1])
			Sleep(1000)
			Return 1
		EndIf
	Else
		;Return
	EndIf

	;Find Right Rare
	Local $ringloc4 = PixelSearch(1920,0,$ringloc2[0]+100,1080,$color)
	If IsArray($ringloc4) Then
		MouseMove($ringloc4[0], $ringloc4[1])
		If $allYellow = 1 Or call("getsum") = 1 Then
			MouseClick("left", $ringloc4[0], $ringloc4[1])
			Sleep(1000)
			Return 1
		EndIf
	Else
		;Return
	EndIf

	Return 0
EndFunc

Func fuzzysleep($ms, $amount = 5)
	For $i=0 To $ms Step 200
		Local $x = MouseGetPos(0)
		Local $y = MouseGetPos(1)
		MouseMove(Random($x-$amount,$x+$amount,1), Random($y-$amount,$y+$amount,1))
		Sleep(100)
	Next
EndFunc

Func takebreak()
	;2.5% chance of Random 45 second Break
	Local $takebreak = Random(1,40,1)
	If $takebreak = 7 Then
		logmessage("Taking 30~60 second break")
		Sleep(Random(30000,60000)) ;rest for 30~60 seconds
		logmessage("Break complete")
	EndIf

	;.5% chance of Random 3~5 minute Break
	$takebreak = Random(1,200,1)
	If $takebreak = 69 Then
		logmessage("Taking 3~5 minute break")
		Sleep(60000*Random(3,5,1)) ;rest for 3-5 minutes
		logmessage("Break complete")
	EndIf

	;.25% chance of Random 5-7 minute Break
	$takebreak = Random(1,400,1)
	If $takebreak = 69 Then
		logmessage("Taking 5~7 minute break")
		Sleep(60000*Random(5,7,1)) ;rest for 8-15 minutes
		logmessage("Break complete")
	EndIf
EndFunc

Func checkdisco($extra = "")
	;Check disco = first is yellow "Network" in popup title
	;            = second is pink "OK" in button text
	Local $coord = PixelSearch(857, 410, 867, 431, 0xEF9900)
	If Not @error Then
		Local $coord2 = PixelSearch(0,0,1920,1080, 0xF3AA55)
		If Not @error Then
				$disconnects = $disconnects + 1
				logmessage("Disconnect #" & $disconnects)
				screenshot("Disco" & $extra)

				; Dismiss the dialog
				fuzzyclick("left", 945, 624)
				$statusDisconnectRecovery = 1
				Return 1
		EndIf
	EndIf

	Return 0
EndFunc

Func getsum($x = 0, $y = -1)
	Send("{CTRLDOWN}")
	Sleep(250)

	Local $a[2]
    $a[0] = $x
    $a[1] = $y


	;Search for Ring
	Local $fingersum = 3692926387
	Local $gray = 0x5B5B5B
    While 1
		;MsgBox(0, "debug", "PRE: "&$a[0] & ", " & $a[1])
        $b = PixelSearch($a[0], $a[1] + 1, 1040, 470, $gray)
        If IsArray($b) Then ; If we found a matching pixel...
			;MsgBox(0, "FOUND", "FOUND: "&$b[0] & ", " & $b[1])

			If PixelCheckSum($b[0], $b[1], $b[0]+27, $b[1]+10) = $fingersum Then
                Send("{CTRLUP}")
				Return 1
            Else
				$a[0] = 0
				$a[1] = $b[1] + 1

				If $a[1] > 470 Then
					;MsgBox(0,"FAILED","FAILED")
					ExitLoop
				EndIf
			EndIf
        Else
            ;MsgBox(0,":(",":(")
			ExitLoop
        EndIf
    Wend

	;amulet color: 0x767676
	;amulet checksum: 2609174597

	;Search for Amulet
	Local $amuletsum = 1085905009
	Local $amuletgray = 0x767676
	$a[0] = $x
    $a[1] = $y

    While 1
		;MsgBox(0, "debug", "PRE: "&$a[0] & ", " & $a[1])
        $b = PixelSearch($a[0], $a[1] + 1, 1040, 470, $amuletgray)
        If IsArray($b) Then ; If we found a matching pixel...
			;MsgBox(0, "FOUND", "FOUND: "&$b[0] & ", " & $b[1])

			If PixelCheckSum($b[0], $b[1], $b[0]+27, $b[1]+10) = $amuletsum Then
                Send("{CTRLUP}")
				Return 1
            Else
				$a[0] = 0
				$a[1] = $b[1] + 1

				If $a[1] > 470 Then
					;MsgBox(0,"FAILED","FAILED")
					ExitLoop
				EndIf
			EndIf
        Else
            ;MsgBox(0,":(",":(")
			ExitLoop
        EndIf
    Wend

	;Search for Demonic Essence
	$demonicessencegray = 0x6F6F6F
	$demonicessencesum = 3808929274
	$a[0] = $x
    $a[1] = $y

	If $demonicEssence = 1 Then
		While 1
			;MsgBox(0, "debug", "PRE: "&$a[0] & ", " & $a[1])
			$b = PixelSearch($a[0], $a[1] + 1, 1040, 470, $demonicessencegray)
			If IsArray($b) Then ; If we found a matching pixel...
				;MsgBox(0, "FOUND", "FOUND: "&$b[0] & ", " & $b[1])
				If PixelCheckSum($b[0], $b[1], $b[0]+27, $b[1]+10) = $demonicessencesum Then
					Send("{CTRLUP}")
					Return 1
				Else
					$a[0] = 0
					$a[1] = $b[1] + 1

					If $a[1] > 470 Then
						;MsgBox(0,"FAILED","FAILED")
						ExitLoop
					EndIf
				EndIf
			Else
				;MsgBox(0,":(",":(")
				ExitLoop
			EndIf
		Wend
	EndIf


	;Search for ilvl63
	$63color = 0x777777
	$63sum = 367647768
	$63sum2 = 2901847775

	$a[0] = 0
    $a[1] = 299

	If $get63s = 1 Then
		While 1
			$b = PixelSearch($a[0], $a[1] + 1, 1040,470, $63color)
			If IsArray($b) Then ; If we found a matching pixel...
				;MsgBox(0, "FOUND", "FOUND: "&$b[0] & ", " & $b[1])
				If PixelCheckSum($b[0], $b[1], $b[0]+20, $b[1]+10) = $63sum Then ;If we're at ilvl
					If PixelCheckSum($b[0]+81, $b[1], $b[0]+97, $b[1]+10) = $63sum2 Then ; If to the right it says 63

						If $getall63s = 1 Then
							Send("{CTRLUP}")
							Return 1
						EndIf

						;Gloves +336,-253
						;gloves checksum = 287465104

						$gloveschecksum = PixelCheckSum($b[0]+336,$b[1]-253,$b[0]+351,$b[1]-243)
						$1handchecksum = PixelCheckSum($b[0]+330,$b[1]-272,$b[0]+340,$b[1]-262)

						$offclass1handchecksum = PixelCheckSum($b[0]+331,$b[1]-181,$b[0]+341,$b[1]-171)
						$offclass1handchecksum2 = PixelCheckSum($b[0]+330,$b[1]-181,$b[0]+340,$b[1]-171)

						;MsgBox(0,"coord",$b[0]+331&","&$b[1]-181&"--"&$b[0]+341&","&$b[1]-171)
						;MsgBox(0,"checksum",$offclass1handchecksum)
						;MouseMove($b[0]+336,$b[1]-253)

						If $gloveschecksum = 287465104 OR $gloveschecksum = 2019578896 OR $gloveschecksum = 1251039451 OR $1handchecksum = 682827412 OR $1handchecksum = 1517296838 OR $offclass1handchecksum = 682827412 OR $offclass1handchecksum = 1517296838 OR $offclass1handchecksum2 = 682827412 OR $offclass1handchecksum2 = 1517296838 Then
							Send("{CTRLUP}")
							Return 1
						Else
							ExitLoop
						EndIf
					Else
						;Found ilvl, but 63 didn't match
						ExitLoop
					EndIf
				Else
					$a[0] = 0
					$a[1] = $b[1] + 19

					If $a[1] > 470 Then
						;MsgBox(0,"FAILED","FAILED")
						ExitLoop
					EndIf
				EndIf
			Else
				;MsgBox(0,":(",":(")
				ExitLoop
			EndIf
		WEnd
	EndIf

	Send("{CTRLUP}")
	Return -1
EndFunc

Func needrepair()
	Local $coord = PixelSearch(1469, 17, 1536, 104, 0xFFEB00)
	If Not IsArray($coord) Then
		$coord = PixelSearch(1469, 17, 1536, 104, 0xDC0000)
	EndIf


	If IsArray($coord) Then
		Return 1
	EndIf

	Return 0
EndFunc

Func repair()
	If Not needRepair() Then
		Return 0
	EndIf

	$statusNeedRepair=1

	;Log
	logmessage("Repairing")

	;Move to Haedrig and repair
	fuzzyclick("left", 1225, 181, 5)
	fuzzysleep(2000)
	;Click repair tab
	fuzzyclick("left", 510, 614, 5)
	fuzzysleep(2000)
	;Click repair all
	fuzzyclick("left", 267, 594, 5)
	fuzzysleep(2000)

	;Take a screenshot for debugging purposes, and to see our gold total
	screenshot( "repair")

	;Exit repair tab
	Send("{ESC}")
	fuzzysleep(500)

	;Move back to start
	fuzzyclick( "left", 666, 849)
	fuzzysleep( 2000)

	If Not needRepair() Then
		$statusRepaired=1
	EndIf
EndFunc

Func repair3()
	If Not needRepair() Then
		Return 0
	EndIf

	$statusNeedRepair=1

	;Log
	logmessage("Repairing Act 3")

	;Move to Haedrig and repair
	fuzzyclick("left", 1348, 26, 5)
	fuzzysleep(5000)
	;Click repair tab
	fuzzyclick("left", 510, 614, 5)
	fuzzysleep(2000)
	;Click repair all
	fuzzyclick("left", 267, 594, 5)
	fuzzysleep(2000)

	;Take a screenshot for debugging purposes, and to see our gold total
	screenshot( "repair")

	;Exit repair tab
	Send("{ESC}")
	fuzzysleep(500)

	;Move back to start
	fuzzyclick( "left", 387, 910)
	fuzzysleep( 5000)

	If Not needRepair() Then
		$statusRepaired=1
		return 1
	EndIf
EndFunc

Func repairadventure()
	If Not needRepair() Then
		Return 0
	EndIf

	$statusNeedRepair=1

	;Log
	logmessage("Repairing Adventure Mode")


	;open map and select act 2 - this is in case we are spawning in act 3. Weird shit happens if we spawn in the act we are repairing in.
	Send("m")
	Sleep(Random(200,500,1))
	call("fuzzyclick", "right", 1088, 517)
	Sleep(Random(400,600,1))
	call("fuzzyclick", "left", 1088, 517)
	Sleep(Random(400,600,1))
	call("fuzzyclick", "left", 1037, 777)
	Sleep(Random(10000,12200,1))
	Sleep($lagfactor)


	;open map and select act 3
	Send("m")
	Sleep(Random(200,500,1))
	call("fuzzyclick", "right", 698, 384)
	Sleep(Random(400,600,1))
	call("fuzzyclick", "left", 698, 384)
	Sleep(Random(400,600,1))
	call("fuzzyclick", "left", 516, 466)
	Sleep(Random(10000,12200,1))
	Sleep($lagfactor)

	;Move to Haedrig and repair
	fuzzyclick("left", 1520, 29, 5)
	fuzzysleep(5000)
	;Click repair tab
	fuzzyclick("left", 510, 614, 5)
	fuzzysleep(2000)
	;Click repair all
	fuzzyclick("left", 267, 594, 5)
	fuzzysleep(2000)

	;Take a screenshot for debugging purposes, and to see our gold total
	screenshot( "repair")

	;Exit repair tab
	Send("{ESC}")
	fuzzysleep(1500)

	If Not needRepair() Then
		$statusRepaired=1
		return 1
	EndIf
EndFunc

Func repair4()
	If Not needRepair() Then
		Return 0
	EndIf

	$statusNeedRepair=1

	;Log
	logmessage("Repairing Act 4")

	;Move to Haedrig and repair
	fuzzyclick("left", 1592, 78, 5)
	fuzzysleep(5000)
	;Click repair tab
	fuzzyclick("left", 510, 614, 5)
	fuzzysleep(2000)
	;Click repair all
	fuzzyclick("left", 267, 594, 5)
	fuzzysleep(2000)

	;Take a screenshot for debugging purposes, and to see our gold total
	screenshot( "repair")

	;Exit repair tab
	Send("{ESC}")
	fuzzysleep(500)

	;Move back to start
	fuzzyclick( "left", 265, 996)
	fuzzysleep( 5000)

	If Not needRepair() Then
		$statusRepaired=1
		return 1
	EndIf
EndFunc

Func getSpecial($num)
	Local $color = 0x99BBFF

	if $num > 4 Then
		logmessage("unable to pickup 'special'")
		screenshot("special failure")
		Return
	EndIf

	;Increment infinite loop counter
	$num = $num + 1

	;Pick up special
	Send("{alt}")
	fuzzysleep(200)
	Local $coord = PixelSearch(200, 0, 1700, 800, 0x99BBFF)

	If Not @error Then
		logmessage( "special found")

		;MsgBox(0, "X and Y are:", $coord[0] & "," & $coord[1])
		MouseClick("left", $coord[0], $coord[1])
		fuzzysleep(2000 * $runspeed)
		getSpecial($num)
	EndIf


EndFunc


Func getLegendaries($num=0)	
	;Exit infinite loop
	If $num > 4 Then
		logmessage( "WARNING - UNABLE TO PICK UP LEGENDARY")
		screenshot( "legendaryfailure")

		;Sleep and allow manual pickup
		If $manualpickup = 1 Then
			Sleep(300000)
		EndIf

		Return
	EndIf

	;Increment infinite loop counter
	$num = $num + 1

	;Pick up legendaries
	Send("{alt}")
	fuzzysleep(200)
	
	Local $coord = PixelSearch(200, 0, 1700, 800, 0xFF8000)

	If Not @error Then
		logmessage( "Legendary Found!")
		screenshot( "legendary")
		$statusLegendaryDrop=1

		;MsgBox(0, "X and Y are:", $coord[0] & "," & $coord[1])
		MouseClick("left", $coord[0], $coord[1])
		fuzzysleep(2000 * $runspeed)
		getLegendaries( $num)
	EndIf

	;Pick up legendaries
	Send("{alt}")
	fuzzysleep(200)
	Local $coord = PixelSearch(200, 126, 1700, 800, 0x00FF00)

	If Not @error Then
		logmessage( "Set Item Found!")
		screenshot( "legendary")
		$statusLegendaryDrop=1

		;MsgBox(0, "X and Y are:", $coord[0] & "," & $coord[1])
		MouseClick("left", $coord[0], $coord[1])
		fuzzysleep(2000 * $runspeed)
		getLegendaries( $num)
	EndIf


EndFunc

Func getGems($num=0)
	;Exit infinite loop
	If $num > 4 Then
		logmessage( "WARNING - UNABLE TO PICK UP GEM")
		screenshot( "gemfailure")

		Return
	EndIf

	;Increment infinite loop counter
	$num = $num + 1

	;Pick up legendaries
	Send("{alt}")
	fuzzysleep(200)
	
	Local $coord = PixelSearch(200, 0, 1700, 800, 0x99BBFF)

	If Not @error Then
		logmessage( "Gem Found!")

		;MsgBox(0, "X and Y are:", $coord[0] & "," & $coord[1])
		MouseClick("left", $coord[0], $coord[1])
		fuzzysleep(2000 * $runspeed)
		getGems( $num)
	EndIf
EndFunc

Func pickupGold($times=2)
	If $getgold = 0 Then
		Return
	EndIf

	Send("{CTRLDOWN}")
	MouseClick("left", MouseGetPos(0)+Random(1,5,1),MouseGetPos(1)+Random(1,5,1))
	For $i=0 to $times
		If checkdead( 0) = 1 Then
			ExitLoop
		EndIf

		Local $goldloc = PixelSearch(1400,700,400,0,0xFFFF8A)
		if IsArray($goldloc) Then
			MouseClick("left",$goldloc[0],$goldloc[1])
			fuzzysleep(Random(600,1000,1) * $runspeed)
		Else
			ExitLoop
		EndIf
	Next
	Send("{CTRLUP}")
EndFunc

Func checkSpiritVesselBuff()
	;first is red of border - second is white of globe
	;each doing the bright and dim checks
	$left=1112
	$top=906
	$right=1270
	$bottom=970
	Local $coord = PixelSearch($left, $top, $right, $bottom, 0x170000)
	If Not @error Then
		Local $coord2 = PixelSearch($left, $top, $right, $bottom, 0x3D3F3F)
		If Not @error Then
			logmessage( "Spirit Vessel Fired")
			Return 1
		EndIf
	EndIf

	; BRIGHT check (not covered by dialog shadow)
	Local $coord = PixelSearch($left, $top, $right, $bottom, 0x740000)
	If Not @error Then
		Local $coord2 = PixelSearch($left, $top, $right, $bottom, 0xF7FFFF)
		If Not @error Then
			logmessage( "Spirit Vessel Fired")
			Return 1
		EndIf
	EndIf

	Return 0
EndFunc

Func getLhoricShrine()
	Local $color1 = 0xD68459
	Local $color2 = 0xDE8F5E
	Local $color3 = 0xE79F6D

	Local $arr = PixelSearch(193,303,266,377,$color1,4)
	If @error Then
		$arr = PixelSearch(193,303,266,377,$color2,4)
		If @error Then
			$arr = PixelSearch(193,303,266,377,$color3,4)
		EndIf
	EndIf

	If Not IsArray($arr) Then
		$arr = PixelSearch(929,38,1010,125,$color1,4)
		If @error Then
			$arr = PixelSearch(929,38,1010,125,$color2,4)
			If @error Then
				$arr = PixelSearch(929,38,1010,125,$color3,4)
			EndIf
		EndIf
	EndIf

	If IsArray($arr) Then
		clickShrine($arr[0], $arr[1])
	EndIf

EndFunc

Func getshrine()
	Local $color1 = 0xD68459
	Local $color2 = 0xDE8F5E
	Local $color3 = 0xE79F6D

	Local $arr = PixelSearch(0,0,1920,630,$color1,4)
	If @error Then
		$arr = PixelSearch(0,0,1920,630,$color2,4)
		If @error Then
			$arr = PixelSearch(0,0,1920,630,$color3,4)
		EndIf
	EndIf

	If IsArray($arr) Then
		clickShrine($arr[0], $arr[1])
	EndIf
EndFunc

Func clickshrine($x,$y)
		$statusShrine=1
		logmessage( "Detected shrine")
		MouseClick("left",$x,$y)
		Sleep(1500 * $runspeed)
		screenshot( "shrine")
		Send("{CTRLDOWN}")
		MouseClick("left",1920-$x,1080-$y)
		Send("{CTRLUP}")
		Sleep(1500 * $runspeed)
EndFunc

Func checkShrineStatus()
	if $statusShrine = 0 Then
		Return
	EndIf

	$statusShrineType = 0

	$color = PixelGetColor(688,914)
	If($color = 0x8E5808) Then
		$statusShrineType = 1 ; Runspeed
	ElseIf($color = 0x592B08) Then
		$statusShrineType = 2 ; Armor
	ElseIf($color = 0x160809) Then
		$statusShrineType = 3 ; Experience
	ElseIf($color=0x653508) Then
		$statusShrineType = 4 ; Magic/Gold Find
	ElseIf($color=0xF3E342) Then
		$statusShrineType = 5 ; Resource/Cooldown
	ElseIf($color=0x371C03) Then
		$statusShrineType = 6 ; Frenzy (Eyeball)
	Endif

	Return $statusShrineType
EndFunc

Func mousePos()
	Local $pos = MouseGetPos()
	MsgBox(0, "Mouse x,y:", $pos[0] & "," & $pos[1] & " -- " & PixelGetColor($pos[0],$pos[1]))
EndFunc

Func theExit()
	writestatustotals()
    Exit
EndFunc

Func exitgame($checkdead = 1)
	;call("screenshot", "PreExit")
	
	;Exit Game
	Send("{ESC}")
	fuzzysleep(50)
	fuzzyclick("left", Random(320,325,1), Random(470,480,1))


	fuzzymove( Random(0,1920,1), Random(0,1080,1))
	fuzzysleep(1000)
	fuzzymove( Random(0,1920,1), Random(0,1080,1))
	fuzzysleep(1000)
	fuzzymove( Random(0,1920,1), Random(0,1080,1))
	fuzzysleep(1000)
	fuzzymove( Random(0,1920,1), Random(0,1080,1))
	fuzzysleep(1000)
	fuzzymove( Random(0,1920,1), Random(0,1080,1))
	fuzzysleep(1000)
	fuzzymove( Random(0,1920,1), Random(0,1080,1))
	fuzzysleep(1000)
	fuzzymove( Random(0,1920,1), Random(0,1080,1))
	fuzzysleep(1000)

	;If ressurect fired by end, log
	If checkSpiritVesselBuff() = 1 Then
		$statusRessurectFired = 1
	EndIf


	;Check if we are dead
	checkdead()

	;Test if we have a "Disconnected" dialog
	checkdisco( "1")

	fuzzymove( Random(0,1920,1), Random(0,1080,1))
	fuzzysleep(1000)
	fuzzymove( Random(0,1920,1), Random(0,1080,1))
	fuzzysleep(1000)
	fuzzymove( Random(0,1920,1), Random(0,1080,1))
	fuzzysleep(1000)
	fuzzymove( Random(0,1920,1), Random(0,1080,1))
	fuzzysleep(Random(0,1000,1))
	;fuzzymove( Random(0,1920,1), Random(0,1080,1))
	;fuzzysleep(1000)

	writestatus()
	resetstatus()

	;Randomly take a break
	If $runs > 10 Then
		takebreak()
	EndIf

	If $runs > $maxruns Then
		If $infinitemode = 1 Then
			logmessage( "Max number of runs has been reached. Sleeping for 6-7 hours.")
			Sleep(Random(1296000,1512000,1))
			$runs = 1
		Else
			logmessage( "Exiting bot. Max number of runs has been reached.")
			theExit()
		EndIf
	EndIf

	;Test if we have a "Disconnected" dialog
	checkdisco( "2")

	;Resume Game
	fuzzyclick("left", 307, 509)
	fuzzysleep(3000)

	;Wait for computer lag
	Sleep($lagfactor)

	Sleep(Random(11000,13000))
EndFunc

Func debugscreenshot()
	If $debug = 1 Then
		screenshot("debug")
	EndIf
EndFunc

Func writeheader()
	logstatus(0,"timestamp,linetype,runs,broken,repaired,shrine,entered,shrineType,ressurect1,legendaryDrop,legendaryFailure,disconnect,died,ressurect2,totalLegends,deathRate")
EndFunc

Func resetstatus()
	$statusNeedRepair=0
	$statusRepaired=0
	$statusShrine=0
	$statusEnteredManor=0
	$statusRessurectOnManorEntrance=0
	$statusLegendaryDrop=0
	$statusLegendaryFailure=0
	$statusDisconnectRecovery=0
	$statusDied=0
	$statusRessurectFired=0
	$statusShrineType=0
EndFunc

;line type 0 == per-run
;line type 1 == totals
Func writestatus()
	;increment total statuses
	$statustotalNeedRepair=$statustotalNeedRepair+$statusNeedRepair
	$statustotalRepaired=$statustotalRepaired+$statusRepaired
	$statustotalShrine=$statustotalShrine+$statusShrine
	$statustotalEnteredManor=$statustotalEnteredManor+$statusEnteredManor
	$statustotalRessurectOnManorEntrance=$statustotalRessurectOnManorEntrance+$statusRessurectOnManorEntrance
	$statustotalLegendaryDrop=$statustotalLegendaryDrop+$statusLegendaryDrop
	$statustotalLegendaryFailure=$statustotalLegendaryFailure+$statusLegendaryFailure
	$statustotalDisconnectRecovery=$statustotalDisconnectRecovery+$statusDisconnectRecovery
	$statustotalDied=$statustotalDied+$statusDied
	$statustotalRessurectFired=$statustotalRessurectFired+$statusRessurectFired

	$deathRate = $statustotalDied / $runs
	logstatus(  1,",0,1," &$statusNeedRepair & "," & $statusRepaired & "," & $statusShrine & "," &	$statusEnteredManor & "," &	$statusShrineType & "," & $statusRessurectOnManorEntrance & "," &	$statusLegendaryDrop & "," &	$statusLegendaryFailure & "," &	$statusDisconnectRecovery & "," &	$statusDied & "," &	$statusRessurectFired & "," & $statustotalLegendaryDrop & "," & $deathRate)

EndFunc

Func writestatustotals()
	logstatus(  1,",1," &$runs&","&$statustotalNeedRepair & "," & $statustotalRepaired & "," & $statustotalShrine & "," &	$statustotalEnteredManor & ",0," &	$statustotalRessurectOnManorEntrance & "," &	$statustotalLegendaryDrop & "," &	$statustotalLegendaryFailure & "," &	$statustotalDisconnectRecovery & "," &	$statustotalDied & "," &	$statustotalRessurectFired)
EndFunc

Func logstatus($usetimestamp,$text)
	Local $time = ""
	Local $file = FileOpen("status.csv", 1)

	If $usetimestamp = 1 Then
		$time = @hour & ":" & @MIN & ":" & @SEC
	EndIf
	; Check if file opened for writing OK
	If $file = -1 Then
		Return
	EndIf

	FileWrite($file, $time)
	FileWrite($file, " " & $text & @CRLF)

	FileClose($file)
EndFunc

Func usepotion()
	Send($potionbutton)
EndFunc
